<?php

namespace App\Service\Message\v1_1_0;

use App\Constants\ErrorCode;
use App\Helpers\ConfigUtil;
use App\Model\CallBase;
use App\Model\UserCoin;
use App\Model\UserProfile;
use App\Model\VideoCallAuditConfig;
use App\Model\VoiceCall;
use App\Model\CallHangup;
use App\Model\User;
use App\Model\VideoCall;
use App\Service\CallBaseService;

/**
 * 随心聊
 */
class QuickCallService extends CallBaseService
{
    protected function RoVerifyList()
    {
        return [
            'call_type' => 'required|string'
        ];
    }

    public function handle()
    {
        $userId = $this->getUserId();
        $callType = $this->request->input('call_type', 1);
        $coinSetting = $callType == VoiceCall::CALL_TYPE ?
            ConfigUtil::getQuickCallCoin('voice') :
            ConfigUtil::getQuickCallCoin('video');
        $callCls = $callType == VoiceCall::CALL_TYPE ? VoiceCall::class : VideoCall::class;

        //个人虚拟币账户信息
        $userCoin = UserCoin::getUserInfo($userId);
        //账户不够支付 3分钟的
        if (!$userCoin || !$userCoin['total_coin'] || $userCoin['total_coin'] < $coinSetting) {
            return $this->setError(ErrorCode::COIN_NOT_ENOUGH, '你的余额不足，请充值后再试~');
        }

        if (VoiceCall::checkUserChatting($userId) || VideoCall::checkUserChatting($userId)) {
            return $this->setError(ErrorCode::HOST_BUSY, '当前正在通话，不能使用该功能～');
        }

        //获取指定的主播
        $hostId = $this->getHostsForMatch($userId, 1, $callType);
        if (!$hostId) {
            $hostId = $this->getHostsForMatch($userId, -1, $callType);
            if (!$hostId) return $this->setError(ErrorCode::NO_VALID_HOST, '当前主播均在忙碌中，请稍后再试~');
        }

        //修改以前无效状态
        $callCls::finishOldCall($userId);

        //发起语音通话
        $ret = $callCls::addRecord($userId, $hostId, CallBase::FROM_QUICK_MESSAGE, $coinSetting);
        //呼叫回调
        $this->callHook($hostId, $userId);
        log_info(__CLASS__ . "=={$callCls}=={$userId}==HostId:{$hostId}");
        // 鉴黄配置
        $config = (new VideoCallAuditConfig())->getConfig($userId);
        return [
            'coin_setting' => $coinSetting,
            'user_info' => UserProfile::buildHostItem(UserProfile::getProfile($hostId)),
            'support_face' => User::checkFaceSupport($hostId),
            'jHConfig' => $config,
        ];
    }
}
